#!/usr/bin/python
import sys

def print_bin_to_q15(n):
    res = -((n>>15) & 1)
    for i in range(15):
        res += float(((n>>i) & 1)) / (2**(15-i))
    print "%x => %f" % (n, res)
    return res


def print_bin_to_q31(n):
    res = -((n>>31) & 1)
    for i in range(31):
        res += float(((n>>i) & 1)) / (2**(31-i))
    print "%x => %f" % (n, res)
    return res


def print_q15_to_bin(q):
    assert(q<1 and q>=-1)
    t = abs(q)
    if q<0:                     # the sign bit
        res = [1]
    else:
        res = [0]

    if t >= 1:
        t -= 1                  # only when q is -1
    for i in range(15):
        t *= 2
        if t >= 1:
            res.append(1)
            t -= 1
        else:
            res.append(0)

    # reverse for negative
    for i in range(1,len(res)):
        if q<0:
            if res[i] == 0:
                res[i] = 1
            else:
                res[i] = 0
    
    bin_val = 0
    for i,v in enumerate(res):
        bin_val += v*(2**(15-i))

    if q<0:
        bin_val += 1
        
    print "%f => %x" % (q, bin_val)
    return bin_val
        
            
def print_q31_to_bin(q):
    assert(q<1 and q>=-1)
    t = abs(q)
    if q<0:                     # the sign bit
        res = [1]
    else:
        res = [0]

    if t >= 1:
        t -= 1                  # only when q is -1
    for i in range(31):
        t *= 2
        if t >= 1:
            res.append(1)
            t -= 1
        else:
            res.append(0)

    # reverse for negative
    for i in range(1,len(res)):
        if q<0:
            if res[i] == 0:
                res[i] = 1
            else:
                res[i] = 0

    bin_val = 0
    for i,v in enumerate(res):
        bin_val += v*(2**(31-i))

    if q<0:
        bin_val += 1
        
    print "%f => %x" % (q, bin_val)
    return bin_val
    



# x = print_q31_to_bin(-0.123)
# print_bin_to_q31(x)
# exit()

    

a = print_bin_to_q15(0xb380)
b = print_bin_to_q15(0x5480)
c = print_bin_to_q15(0x1eb6)

prod = a*b
print "%f * %f = %f" % (a, b, prod)
print_q31_to_bin(prod)
print_q31_to_bin(-prod)


print_bin_to_q31(0xe6bfc000<<1)


print_bin_to_q31(0xb2808000)

print_q31_to_bin(0.634475194336)
print_q31_to_bin(0.634475194336+2**(-16))

exit()


    
print_bin_to_q31(0x5136)
print_bin_to_q31(0x5137)


print_q31_to_bin(0.634475194336)

n = int(sys.argv[1], 16)
print_bin_to_q15(n)

print_q15_to_bin(-0.12345)
print_q15_to_bin(-1)


print_bin_to_q15(0x7e83)
print_bin_to_q15(0xde01)
print_bin_to_q15(0x4879)

print_q15_to_bin(0.828698938562)

print_q15_to_bin(-0.15461719433599996)

